package com.crazy.jiakoulachang.service.impl;

import com.alibaba.excel.EasyExcel;
import com.crazy.jiakoulachang.common.Constant;
import com.crazy.jiakoulachang.mapper.ProductMapper;
import com.crazy.jiakoulachang.mapper.UserMapper;
import com.crazy.jiakoulachang.pojo.Product;
import com.crazy.jiakoulachang.pojo.User;
import com.crazy.jiakoulachang.service.ProductService;
import com.crazy.jiakoulachang.vo.DetailsVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author: 卢辉宇
 * @date: 2023/3/15 21:43
 * @description:
 */
@Service
public class ProductServiceImpl implements ProductService {
    @Resource
    ProductMapper productMapper;

    @Resource
    UserMapper userMapper;


    @Transactional
    @Override
    public void add(String userName, String number, String productType, Double weight, String details) {
        //判断用户是否存在
        if (number==null)
            number="无";
        User user = userMapper.selectByNameAndNumber(userName, number);
        if (user == null) {
            //用户不存在,插入用户表
            userMapper.insert(userName, number);
            //重新查询
            user = userMapper.selectByNameAndNumber(userName, number);
        }

        Double price = null;
        switch (productType) {
            case "腊肠":
                price = Constant.SAUSAGE_PRICE;
                break;
            case "腊肉":
                price = Constant.BACON_PRICE;
                break;
            case "烘干":
                price = Constant.OVEN_DRY_PRICE;
                break;
        }
        //准备数据封装成product对象
        Product product = new Product();
        product.setUserId(user.getUserId());
        product.setProductType(productType);
        product.setPrice(price);
        product.setWeight(weight);
        product.setReceivable((Math.round(price * weight * 100) / 100.0));//保留两位小数
        product.setCreateTime(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        product.setDetails(details);

        productMapper.insert(product);


    }


    @Override
    public PageInfo getPage(int currentPage, int pageSize) {
        PageHelper.startPage(currentPage, pageSize);
        List<DetailsVO> detailsVOList = productMapper.selectAll();
        for (int i = 0; i < detailsVOList.size(); i++) {
            DetailsVO detailsVO = detailsVOList.get(i);
//            System.out.println(detailsVO);

        }
        //把查到的全部目录列表封装成PageInfo
        PageInfo pageInfo = new PageInfo(detailsVOList);
        return pageInfo;
    }


    @Override
    public PageInfo selectNotPay(int currentPage, int pageSize) {
        PageHelper.startPage(currentPage, pageSize);
        List<DetailsVO> detailsVOList = productMapper.selectByNetReceipts();
        for (int i = 0; i < detailsVOList.size(); i++) {
            DetailsVO detailsVO = detailsVOList.get(i);
//            System.out.println(detailsVO);

        }
        //把查到的全部目录列表封装成PageInfo
        PageInfo pageInfo = new PageInfo(detailsVOList);
        return pageInfo;
    }

    @Override
    public PageInfo selectByCreateTime(int currentPage, int pageSize, String startTime, String endTime) {
        PageHelper.startPage(currentPage, pageSize);
        List<DetailsVO> detailsVOList = productMapper.selectByCreateTime(startTime,endTime);
        for (int i = 0; i < detailsVOList.size(); i++) {
            DetailsVO detailsVO = detailsVOList.get(i);
//            System.out.println(detailsVO);

        }
        //把查到的全部目录列表封装成PageInfo
        PageInfo pageInfo = new PageInfo(detailsVOList);
        return pageInfo;
    }

    /**
     * 导出到excel表格
     * @param response
     */
    @Override
    public void exportData(HttpServletResponse response) throws IOException {
        //设置下载信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String date=new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String fileName = URLEncoder.encode("未付款订单导出（"+date+")", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        List<DetailsVO> detailsVOList = productMapper.selectByNetReceipts();
        //   DetailsVO.class 是按导出类  detailsVOList应为数据库查询数据
        EasyExcel.write(response.getOutputStream(), DetailsVO.class).sheet("模板").doWrite(detailsVOList);

    }

    @Override
    public void downByCreateTime(HttpServletResponse response, String startTime, String endTime) throws IOException {
        //设置下载信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String date=new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String fileName = URLEncoder.encode(startTime+"到"+endTime+"订单导出（"+date+"）", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        List<DetailsVO> detailsVOList = productMapper.selectByCreateTime(startTime,endTime);
        //   DetailsVO.class 是按导出类  detailsVOList应为数据库查询数据
        EasyExcel.write(response.getOutputStream(), DetailsVO.class).sheet("指定日期所有订单").doWrite(detailsVOList);
    }

    @Transactional
    @Override
    public void sale(String productType, Double weight, Double price, String details) {
        //准备数据封装成product对象
        Product product = new Product();
        product.setProductType(productType);
        product.setPrice(price);
        product.setWeight(weight);
        product.setReceivable((Math.round(price * weight * 100) / 100.0));//保留两位小数
        product.setCreateTime(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        product.setDetails(details);

        productMapper.insert(product);
    }

    @Transactional
    @Override
    public void saleEdit(Integer productId, String productType, Double weight, Double price, Double netReceipts, String details) {
        //准备数据封装成product对象
        Product product = new Product();
        product.setProductType(productType);
        product.setPrice(price);
        product.setWeight(weight);
        product.setReceivable((Math.round(price * weight * 100) / 100.0));//保留两位小数
        product.setDetails(details);

        Double netReceiptsByProductId = productMapper.selectNetReceiptsByProductId(productId);
        if (netReceipts != 0) {
            product.setNetReceipts(netReceipts);//保留两位小数
            if (netReceiptsByProductId == null) {
                //只记录第一次收款时间，后面修改的不计入
                product.setTime(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));//收款时间
            }
        }
        productMapper.updateByProductId(product, productId);
    }

    @Override
    public Double selectGeneralIncomeByCreateTime(String startTime, String endTime) {
        Double generalIncome = productMapper.selectGeneralIncomeByCreateTime(startTime, endTime);
        if(generalIncome==null){
            generalIncome=0.0;
        }
        return generalIncome;
    }


    @Override
    public void deleteByProductId(Integer productId) {
        productMapper.deleteByProductId(productId);
    }

    @Transactional
    @Override
    public void updateProductAndUser(Integer productId, String userName, String number, String productType, Double weight, Double netReceipts, String details) {
        //判断用户是否存在
        User user = userMapper.selectByNameAndNumber(userName, number);
        if (user == null) {
            //用户不存在,插入用户表
            userMapper.insert(userName, number);
            //重新查询
            user = userMapper.selectByNameAndNumber(userName, number);
        }

        Double price = null;
        switch (productType) {
            case "腊肠":
                price = Constant.SAUSAGE_PRICE;
                break;
            case "腊肉":
                price = Constant.BACON_PRICE;
                break;
            case "烘干":
                price = Constant.OVEN_DRY_PRICE;
                break;
        }
        //准备数据封装成product对象
        Product product = new Product();
        product.setUserId(user.getUserId());
        product.setProductType(productType);
        product.setPrice(price);
        product.setWeight(weight);
        product.setReceivable((Math.round(price * weight * 100) / 100.0));//保留两位小数
        product.setDetails(details);

        Double netReceiptsByProductId = productMapper.selectNetReceiptsByProductId(productId);
        if (netReceipts != 0) {
            product.setNetReceipts(netReceipts);//保留两位小数
            if (netReceiptsByProductId == null) {
                //只记录第一次收款时间，后面修改的不计入
                product.setTime(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));//收款时间
            }
        }
        productMapper.updateByProductId(product, productId);

    }

}
